//
//  CommonSectionTableController.m
//  EUCIOS
//
//  Created by Khang on 3/31/13.
//  Copyright (c) 2013 Khang. All rights reserved.
//

#import "CommonTableViewController.h"
#import "CommonSectionTableController.h"

@interface CommonSectionTableController ()

@end

@implementation CommonSectionTableController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.sections = [NSMutableArray array];
    }
    return self;
}

- (id)init {
    if (self = [self initWithStyle:UITableViewStylePlain]) {
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
    if (self.sections) {
        [self.sections removeAllObjects];
        self.sections = nil;
    }
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if ([self.sections count] > 0) {
        return [self.sections count];
    }
    
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section >= 0 && section < [self.sections count]) {
        NSMutableArray* items = [self.items objectAtIndex:section];
        return [items count];
    }
    
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    id objectSection = [self.sections objectAtIndex:section];
    if (objectSection) {
        return [NSString stringWithFormat:@"%@", objectSection];
    }
    return @"";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Class cellClass = [self cellClassForObject:[[self.items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]
                                   ofTableView:tableView];
    NSString* cellIdentifier = NSStringFromClass(cellClass);
    CommonTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell) {
        cell = [[cellClass alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    
    if ([cell isKindOfClass:[CommonTableCell class]]) {
        [cell setObject:[[self.items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]];
    }
    
    return cell;
}

#pragma mark -
#pragma mark Table view delegate
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [super tableView:tableView viewForHeaderInSection:section];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    id object = [[self.items objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    Class cellClass = [self cellClassForObject:object ofTableView:tableView];
    return [cellClass heightForCellWithObject:object ofTableView:tableView];
}

@end
